package com.haoe.service.impl;

import com.google.common.collect.Lists;
import com.haoe.common.CommonResult;
import com.haoe.common.constant.Constants;
import com.haoe.dto.DishDTO;
import com.haoe.dto.query.OrderInfoQuery;
import com.haoe.entity.Customer;
import com.haoe.entity.Order;
import com.haoe.entity.OrderDish;
import com.haoe.enums.OrderStatusEnum;
import com.haoe.mapper.CustomerMapper;
import com.haoe.mapper.OrderDishMapper;
import com.haoe.service.CustomerService;
import com.haoe.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Author: 80305082
 * @Date: 2021/3/12
 * @Description: 顾客service实现类
 */
@Service
@Slf4j
public class CustomerServiceImpl implements CustomerService {

    @Resource
    private CustomerMapper customerMapper;

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderDishMapper orderDishMapper;

    @Override
    public Customer getCustomerInfo(Long id) {
        if (Objects.isNull(id)) {
            return null;
        }
        return customerMapper.selectById(id);
    }

    @Override
    public CommonResult submitOrder(OrderInfoQuery orderInfoQuery) throws Exception {
        try {
            Order order = Order.builder().customerId(orderInfoQuery.getCustomerId()).
                    createdOn(orderInfoQuery.getCreatedOn())
                    .restaurantId(orderInfoQuery.getRestaurantId())
                    .status(0).build();
            // 首先查看是否存在未完成(未支付)的订单
            List<Order> orderList = orderService.selectByCustomerIdAndRestaurantId(orderInfoQuery.getCustomerId(), orderInfoQuery.getRestaurantId());
            if (!orderList.isEmpty()) {
                List<Integer> statusList = orderList.stream().map(Order::getStatus).collect(Collectors.toList());
                if (statusList.contains(OrderStatusEnum.SUBMIT.getCode())) {
                    throw new Exception("存在未支付的订单");
                }
            }
            // 这里返回的时插入成功后的条数
            orderService.saveOrder(order);
            // 自行获取插入成功后的主键id，使用get方法
            Long orderId = order.getId();
            log.info("submitOrder id:{}", orderId);
            // 插入Order_dish
            batchSaveOrderDish(orderInfoQuery, orderId);
        } catch (Exception e) {
            log.error("提交订单异常:{}", e.getMessage());
            throw new Exception(e.getMessage());
        }

        return CommonResult.success(null);
    }

    @Override
    public void batchSaveOrderDish(OrderInfoQuery orderInfoQuery, Long orderId) throws Exception {
        List<OrderDish> orderDishList = getOrderDishes(orderInfoQuery, orderId);
        if (orderDishList.isEmpty()) {
            log.error("没有发现客官您的菜菜呢！请添加菜菜哟~");
            throw new Exception("没有发现客官您的菜菜呢！请添加菜菜哟~");
        }
        // 使用批量插入方式
        // 每次最多插入500条
        int size = orderDishList.size();
        for (int i = 0; i < size; i += Constants.MAX_SIZE) {
            List<OrderDish> list = orderDishList.subList(i, Integer.min(size, i + Constants.MAX_SIZE));
            int res = orderDishMapper.batchSave(list);
            if (res < list.size()) {
                throw new Exception("没有添加全部点菜菜品，请重试");
            }
        }
    }

    public List<OrderDish> getOrderDishes(OrderInfoQuery orderInfoQuery, Long orderId) {
        List<DishDTO> dishDTOList = orderInfoQuery.getDishDTOList();
        List<OrderDish> orderDishList = Lists.newArrayList();
        for (DishDTO dishDto : dishDTOList) {
            OrderDish orderDish = OrderDish.builder().orderId(orderId).count(dishDto.getCount()).menuDishId(dishDto.getDish().getId()).build();
            orderDishList.add(orderDish);
        }
        return orderDishList;
    }
}
